package cn.muqingfeng.util;

import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import cn.muqingfeng.api.to.Article1TO;
import cn.muqingfeng.api.to.ArticleTO;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ArticleCache {

	private static final String FILE_NAME = ".cache.xml";

	public static final void saveArticle(Context context, String url, List<ArticleTO> articles) {
		SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		Gson gson = new Gson();
		editor.putString(getCacheKey(url), gson.toJson(articles));
		editor.putLong(getCacheKey(url + "#time"), System.currentTimeMillis());
		editor.commit();
	}

	public static final List<ArticleTO> getArticles(Context context, String url) {
		SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		String articlString = preferences.getString(getCacheKey(url), null);
		if (!TextUtils.isEmpty(articlString)) {
			Gson gson = new Gson();
			return gson.fromJson(articlString, new TypeToken<List<ArticleTO>>() {
			}.getType());
		}
		return null;
	}

	public static final void saveArticle1(Context context, String url, List<Article1TO> articles) {
		SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		Gson gson = new Gson();
		editor.putString(getCacheKey(url), gson.toJson(articles));
		editor.putLong(getCacheKey(url + "#time"), System.currentTimeMillis());
		editor.commit();
	}

	public static final List<Article1TO> getArticles1(Context context, String url) {
		SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		String articlString = preferences.getString(getCacheKey(url), null);
		if (!TextUtils.isEmpty(articlString)) {
			Gson gson = new Gson();
			return gson.fromJson(articlString, new TypeToken<List<Article1TO>>() {
			}.getType());
		}
		return null;
	}

	public static final long getLastRefreshTime(Context context, String url) {
		SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		return preferences.getLong(getCacheKey(url + "#time"), 0);
	}

	private static final String getCacheKey(String key) {
		return MD5Util.encode(key, false);
	}

	public static final void clearCache(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		preferences.edit().clear().commit();
	}
}
